<template>
  <el-dialog :title='titleName' :close-on-click-modal="false" :close-on-press-escape="false" :show-close='false'
    :visible.sync="dialogPeople" @close="dialogClose" custom-class="el-dialog-box" @open="peopleEditOpen">
    <el-container>
      <el-aside style="float:left;width: 300px;">
        <el-card class="box-card el-card-flex">
          <!--树状图搜索框 -->
          <div slot="header" class="clearfix">
            <el-input placeholder="按机构名称查询" suffix-icon="el-icon-search" v-model="filterText" clearable></el-input>
          </div>
          <!-- 树状图 -->
          <div class="text item el-over-auto">
            <el-tree :highlight-current="true" class="filter-tree" :data="dataTree" v-show="filterText"
              default-expand-all :load="loadNode" :props="defaultProps" ref="tree" node-key="orgId" @node-click="handleNodeClick"></el-tree>
            <el-tree :highlight-current="true" class="filter-tree" v-show="filterText=='' " :load="loadNode"
              :default-expanded-keys="treeExpandedKey" :props="defaultProps" ref="tree" node-key="orgId" lazy
              @node-click="handleNodeClick" :key="keyTree"></el-tree>
          </div>
        </el-card>
      </el-aside>
      <el-main style="padding:0 0 0 10px;" class="el-box-column">
        <!-- 卡片 -->
        <!-- 新增岗位-->
        <el-card class="el-flex el-card-flex ">
          <div slot="header" class="clearfix">
            <span>岗位列表</span>
          </div>
          <div class="text item el-over-auto" style="display: block;">
            <el-tag size="medium" class="jobListTag" style="cursor: pointer;" :effect="tag.effect" :key="index" v-for="(tag,index) in dynamicTags"
              closable @close="handleClose(tag.positionId)" @click="tagClick(index,tag)">
              {{tag.posiName}}
            </el-tag>
            <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
              @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
            </el-input>
            <el-button v-else class="button-new-tag" @click="showInput"> 新增岗位 <i class="el-icon-upload el-icon-plus"></i></el-button>
          </div>
        </el-card>
        <!-- 已选岗位-->
        <el-card style="margin-top:10px;" class="el-flex el-card-flex">
          <div slot="header" class="clearfix">
            <span>分配关系</span>
          </div>
          <div class="text item el-over-auto" style="display: block;">
            <!-- 新增所选岗位 -->
            <el-tag size="medium" class="jobListTag" style="cursor: pointer;" effect="dark" closable :key="check.positionId"
              :title="check.fullName + check.posiName" v-for="(check,index) in editDataEdit.positions" @close="handleCloseCheckedAdd(index)">
              {{check.shortName?check.shortName:check.orgCode+"-"+check.posiName}}
            </el-tag>
          </div>
        </el-card>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSave">确定 <i class="el-icon-document-checked"></i></el-button>
      <el-button @click="handleCloseDialog">取消 <i class="el-icon-refresh-left"></i></el-button>
    </span>
  </el-dialog>
</template>
<script>
  import {
    Tree,
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    tag
  } from 'element-ui'
  import {
    organizationSearch,
    organizationRoot,
    organizationParent,
    empPositionRelation,
    employeeAddOrEdit
  } from '@/api/org/peoplemanage/peoplemanage.js'
  import {
    empPositionRelationRemove,
    searchAllOrgPosition,
    orgPositionNew,
    empPositionRelationDelete,
    empPositionPositionIds
  } from '@/api/org/peoplemanage/peopleEdit.js'
  export default {
    name: 'PeopleEdit',
    components: {
      'el-tree': Tree, //树形菜单
      'el-dialog': Dialog, //对话框
      'el-tag': tag,
    },
    props: ["dialogPeople", "editDataEdit", 'initialeditData', 'changeTitle', 'justJobEdit'],
    data() {
      return {
        cancelFlag: '',
        treeExpandedKey: [],
        dynamicTags: [], //标签数据源
        checkTag: [], //已选标签数据源
        inputVisible: false,
        inputValue: '',
        keyTree: 1,
        filterText: '',
        dataTree: [], //树形图初始化
        defaultProps: {
          label: 'orgName',
          isLeaf: 'leaf'
        },
        showBtton: false,
        dialogVisible: false,
        dialogAdd: false,
        pageSize: 20,
        total: 0,
        currentPage: 1,
        personalName: "",
        tableData: [], //树形图初始数据
        addUser: [], //下拉人员初始化
        addGender: [], //下拉性别
        addStatus: [], //人员状态
        currentTreeData: {},
        tagClickData: '', //当前点击标签数据源
        colorChange: "",
        checked: false,
        orgId: "",
        editAry: [],
        orgCode: "",
        titleName: '员工分配',
        initialDatas: {}
      };
    },
    watch: {
      filterText(val) { //树查询
        if (val) {
          organizationSearch(val).then(res => {
            this.removeTip() //移除默认提示
            this.deepChild(res.data.data);
            this.dataTree = res.data.data
          })
        } else {
          this.filterText = ""
          this.keyTree += 1
        }
      }
    },
    methods: {
      /*移除默认提示 */
      removeTip() {
        let msgs = document.getElementsByClassName("el-message")
        for (let i = 0, len = msgs.length; i < len; i++) {
          msgs[i].style.display = "none";
        }
      },
      /* 递归遍历树形数据源 */
      deepChild(val) {
        let $this = this;
        if (val && Array.isArray(val) && val.length) {
          val.forEach(item => {
            if (typeof item === 'object') {
              item.orgId = item.id;
              item.orgName = item.name;
              $this.deepChild(item.children);
            }
          })
        }
      },
      loadNode(node, resolve) { //树形图父节点
        if (node.level === 0) {
          organizationRoot().then(res => {
            res.data.data.forEach(e => {
              e.leaf = e.isLeaf == 'y' ? true : false;
            });
            resolve(res.data.data);
            this.orgId = res.data.data[0].orgId
            this.$refs.tree.setCurrentKey(this.orgId);
            this.treeExpandedKey = [this.orgId];
            this.handleJobAll(this.orgId)
          }).catch(res => {
            resolve([])
          })
        } else {
          let id = node.data.orgId
          this.orgId = id
          let childrenDatas = {
            'id': node.data.orgId,
            'page': 0,
            'size': 0
          }
          organizationParent(childrenDatas).then(res => {
            res.data.data.records.forEach(e => {
              e.leaf = e.isLeaf == 'y' ? true : false;
            });
            resolve(res.data.data.records)
          }).catch(res => {
            resolve([])
          })
        }
      },
      handleNodeClick(data) { //点击树形图 表格数据加载
        this.orgCode = data.orgCode
        this.currentTreeData = data
        this.orgId = data.orgId
        this.handleJobAll(data.orgId) //获取当前所有岗位
      },
      handleSave() { //确认
        if (this.editDataEdit.positions.length != 0) {
          if (this.changeTitle != '新增人员') {
            let arr1 = []
            let arr2 = []
            this.initialeditData.positions.forEach(item => {
              arr1.push(item.positionId)
            })
            this.editDataEdit.positions.forEach(item => {
              arr2.push(item.positionId)
            })
            let SamePart = arr1.filter(item => arr2.includes(item))
            let Difference = arr1.filter(item => !SamePart.includes(item))
            Difference.forEach(item => {
              empPositionRelationRemove(this.initialeditData.empId, item)
            })
          }
          if (this.justJobEdit == 'true') {
            let ids = []
            this.editDataEdit.positions.forEach(item => {
              ids.push(item.positionId)
            })
            employeeAddOrEdit({
              "empId": this.editDataEdit.empId,
              "empName": this.editDataEdit.empName,
              "empCode": this.editDataEdit.empCode,
              "empStatus": this.editDataEdit.empStatusId,
              "empStatusId": this.editDataEdit.empStatus,
              "orgId": this.editDataEdit.orgId,
              "gender": this.editDataEdit.genderId,
              "genderId": this.editDataEdit.gender,
              "userName": this.editDataEdit.userName,
              "mobileNo": this.editDataEdit.mobileNo,
              "positions": ids
            }).then(res => {
              this.$emit("peopleDialog", false)
              this.$emit("refreshTable")
            })
          } else {
            this.editDataEdit.positions.forEach(item => {
              if (!item.shortName) {
                item.shortName = item.orgCode + "-" + item.posiName
              }
              if (!item.fullName) {
                item.fullName = item.orgCode + "-" + item.posiName
              }
            })
            this.$emit("jobEdit", this.editDataEdit.positions)
            this.$emit("peopleDialog", false)
          }
        } else {
          Message({
            type: 'warning',
            message: '请选择分配关系'
          })
        }
      },
      // handleCloseDialog() {
      //   if (this.changeTitle == '新增人员') {
      //     this.$emit("jobEdit", [])
      //   } else {
      //     this.initialDatas =JSON.parse(JSON.stringify(this.initialeditData.positions))
      //     this.$emit("jobEdit", this.initialDatas)
      //   }
      //   this.$emit("peopleDialog", false)
      // },
      handleCloseDialog() {
        if (this.initialeditData.positions.length == 0) {
          this.$emit("jobEdit", [])
        } else {
          this.initialDatas = JSON.parse(JSON.stringify(this.initialeditData.positions))
          this.$emit("jobEdit", this.initialDatas)
        }
        this.$emit("peopleDialog", false)
      },
      dialogClose() { //弹框关闭X按钮事件
        this.$emit("peopleDialog", false)
      },
      handleClose(id) { //标签关闭
        empPositionRelationDelete(id).then(res => {
          this.handleJobAll(this.orgId)
        }).catch(res => {})
      },
      handleCloseCheckedAdd(id) { //新增标签关闭
        this.editDataEdit.positions.splice(id, 1);
      },
      tagClick(index, data) { //点击岗位标签
        data.effect = "dark";
        let cData = this.$refs.tree.getCurrentNode();
        data.orgCode = cData.orgCode;
        data.fullName = cData.orgName;
        var oldLen = this.editDataEdit.positions.length;
        this.editDataEdit.positions.push(data)

        function Es6duplicate(arr, type) { //去重
          if (arr.length == 0) {
            return arr;
          } else {
            if (type) {
              var obj = {}
              var newArr = arr.reduce((cur, next) => {
                obj[next.positionId] ? "" : obj[next.positionId] = true && cur.push(next);
                return cur;
              }, [])
              return newArr;
            } else {
              return Array.from(new Set(arr));
            }
          }
        }
        var ary = Es6duplicate(this.editDataEdit.positions, "positionId")
        if (ary.length == oldLen) {
          Message({
            type: 'warning',
            message: '该岗位已分配'
          });
        }
        this.editDataEdit.positions = ary
      },
      showInput() { //标签新增input显示隐藏
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() { //标签新增成功
        let inputValue = this.inputValue;
        if (inputValue) {
          orgPositionNew({
            "posiName": inputValue,
            "orgId": this.orgId
          }).then(res => {
            this.handleJobAll(this.orgId)
          }).catch(res => {})
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleJobAll(orgId) { //查询所有岗位
        searchAllOrgPosition(orgId).then(res => {
          this.dynamicTags = res.data.data
          this.dynamicTags.forEach(item => {
            item.effect = "light";
          })
        }).catch(res => {})
      },
      peopleEditOpen() {
        this.keyTree += 1
      }
    }
  };
</script>

<style lang="scss">
  .el-dialog-box {
    height: 90%;
    display: flex;
    flex-direction: column;

    .el-dialog__body {
      flex: 1;

      .jobListTag {
        margin-bottom: 10px
      }

      .jobListTag:first-child {
        margin-left: 10px
      }
    }
  }

  .changeColor {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
  }

  .el-card__body {
    position: relative;

  }

  .el-tag.el-tag--medium {
    height: 32px;
    line-height: 30px;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
  }
</style>
